package com.puyuba.puyuba.view.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.puyuba.puyuba.R;
import com.puyuba.puyuba.SkinApplication;
import com.pyb.java.basemodule.BaseFragment;
import com.puyuba.puyuba.bean.GetStudentBean;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.network.RequestBodyUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;

import com.pyb.java.network.scheduler.RxSchedulers;
import com.puyuba.puyuba.network.UserApi;
import com.pyb.java.commonutil.utils.NetUtil;
import com.pyb.java.commonutil.ToastHelper;

import com.puyuba.puyuba.view.adapter.GetStudentAdatper;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;

import java.util.HashMap;

import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

/**
 * 消息模块第三个fragment 找学生页面
 */
public class MessageFindStudentFragment extends BaseFragment {
    private EditText etStudent;
    private TextView tvSearchStu;
    private SmartRefreshLayout srlMsgStu;
    private RecyclerView rclListFindstu;
    private String name = "";
    private int localpage = 1;//本地加载的页数
    private int last_page = 1;//最大有几页
    private GetStudentAdatper mAdapter;

    @Override
    public void initView() {
        etStudent = (EditText) getActivity().findViewById(R.id.et_student);
        tvSearchStu = (TextView) getActivity().findViewById(R.id.tv_search_stu);
        srlMsgStu = (SmartRefreshLayout) getActivity().findViewById(R.id.srl_msg_stu);
        rclListFindstu = (RecyclerView) getActivity().findViewById(R.id.rcl_list_findstu);

        initListener();

        rclListFindstu.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new GetStudentAdatper(R.layout.item_message_one);
        mAdapter.bindToRecyclerView(rclListFindstu);

        srlMsgStu.setRefreshHeader(new ClassicsHeader(getContext()));
        srlMsgStu.setRefreshFooter(new ClassicsFooter(getContext()));
        srlMsgStu.setOnRefreshListener(refreshlayout -> {
            boolean mobileConnected = NetUtil.isNetworkAvailable(SkinApplication.sContext);
            if (mobileConnected) {
                localpage = 1; //每次下拉刷新 都置为1
                getstudents(0,0, CacheUserInfo.getInstance().getId(),name,false);
            } else {
                ToastHelper.showToast("网络未连接，请检查网络状态");
                if (srlMsgStu!= null){
                    srlMsgStu.finishRefresh();
                }
            }
        });
        srlMsgStu.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                boolean mobileConnected = NetUtil.isNetworkAvailable(SkinApplication.sContext);
                if (mobileConnected) {
                    localpage++;
                    getstudents(localpage,0, CacheUserInfo.getInstance().getId(),name,true);
                } else {
                    ToastHelper.showToast("网络未连接，请检查网络状态");
                    if (srlMsgStu!= null){
                        srlMsgStu.finishLoadMore();
                    }
                }
            }
        });
        getstudents(0,0, CacheUserInfo.getInstance().getId(),name,false);
    }

    private void initListener() {
        tvSearchStu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = etStudent.getText().toString().trim();
                getstudents(0,0, CacheUserInfo.getInstance().getId(),name,false);
            }
        });
    }

    //查询学生
    private void getstudents(int page,int size,int uid,String keyword,boolean isLoadMore) {
        if (!isLoadMore) {
            localpage = 1;
        }
        showLoadingDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("size", size);
        map.put("uid", uid);
        map.put("keyword", keyword);
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);
        RetrofitManger.getInstance().createService(UserApi.class)
                .getstudents(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<GetStudentBean>>applySchedulers())
                .subscribe(new ResponseObserve<GetStudentBean>(){

                    @Override
                    public void onSuccess(ResponseEntity<GetStudentBean> responseEntity) {
                        closeLoadingDialog();

                        if (localpage <= last_page && localpage != 1) {
                            mAdapter.addData(responseEntity.getData().getList());
                        } else {
                            mAdapter.setNewData(responseEntity.getData().getList());
                        }
                        last_page = responseEntity.getData().getPage().getLast_page();
                        if (localpage >= last_page) {
                            srlMsgStu.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
                        } else {
                            srlMsgStu.finishLoadMore();      //加载完成
                        }
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        closeLoadingDialog();
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        if (srlMsgStu!= null){
                            srlMsgStu.finishRefresh();
                        }
                    }
                });

    }

    public static MessageFindStudentFragment getInstance(String type) {
        MessageFindStudentFragment messageOneFragment = new MessageFindStudentFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        messageOneFragment.setArguments(args);
        return messageOneFragment;
    }
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_message_find_student;
    }

}
